class UsersController < ApplicationController
  before_action :logged_in_user, only: :index
  before_action :correct_user, only: [:edit, :update]
  before_action :admin_user, only: :destroy
  def index
    @users = User.paginate(page: params[:page])
  end
  def new
    @user = User.new
  end
  def show
    @user = User.find(params[:id])
    flash[:fail] = "权限不足"
    redirect_to root_url()
  end
  def create
    @user = User.new(user_params)
    if @user.save
      #log_in @user
      UserMailer.account_activation(@user).deliver_now
      flash[:success] = "验证邮件已发送，请您注意查收！"
      redirect_to root_url()
    else
      flash[:fail] = @user.errors.full_messages.first
      redirect_to signup_url()
    end
  end
  def edit
    @user = User.find(params[:id])
  end
  def update
    @user = User.find(params[:id])
    if @user.update(user_params)
      flash[:success] = "编辑成功"
      redirect_to root_url()
    else
      flash[:fail] = "编辑失败：" + "参数不合规"
      render 'edit'
    end
  end
  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "已删除用户"
    redirect_to users_url
  end

  private

    def user_params
      params.require(:user).permit(:name, :email, :password,
      :password_confirmation)
    end
    def user_params
      params.require(:user).permit(:name, :password,
      :password_confirmation)
    end

    def logged_in_user
      unless logged_in?
        flash[:fail] = "权限不足"
        redirect_to login_url
      end
    end
    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_url) and flash[:fail] = "权限不足" unless current_user?(@user)
    end
    def admin_user
      redirect_to(root_url) and flash[:fail] = "权限不足" unless current_user.admin?
    end
end
